package com.jxs.android.weiget;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PointF;
import android.text.SpannableString;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.jxs.android.weiget.HorizontalScrollPane.HScrollViewListener;
import com.jxs.android.weiget.VerticalScrollPane.VScrollViewListener;
import com.jxs.android.ges.R;

public class ReportContainer extends LinearLayout implements HScrollViewListener, VScrollViewListener {
	private static final int FULL_ROW_NUM = 16 + 1;
	private String mReportName;
	private int mYear, mMonth, mDay;
	private String newDate;

	private HorizontalScrollPane mHPan;
	private HorizontalScrollPane mHHeadPan;
	private VerticalScrollPane mVPan;
	private TableLayout mTableBody;
	private TableLayout mTableHeader;
	private TableLayout mTableVHeader;
	private TextView mCorner;
	private ImageView mIndicatorV, mIndicatorH;

	private Context mContext;
	private List<String> mTitles;
	private int mRowIndex = 0;

	private View.OnClickListener cellListener;

	public ReportContainer(Context context) {
		this(context, null);
	}

	public ReportContainer(Context context, AttributeSet attrs) {
		super(context, attrs);
		initData();
		initView(context);
	}

	private void initData() {
		mTitles = new ArrayList<String>();
	}

	private void initView(Context context) {
		mContext = context;

		LayoutInflater flater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		flater.inflate(R.layout.bu_tab_scroll_view, this);

		mCorner = (TextView) findViewById(R.id.corner);
		mTableHeader = (TableLayout) findViewById(R.id.table_header);
		mTableVHeader = (TableLayout) findViewById(R.id.table_vheader);
		mTableBody = (TableLayout) findViewById(R.id.table_body);

		mTableHeader.setStretchAllColumns(true);
		mTableBody.setStretchAllColumns(true);

		mHPan = (HorizontalScrollPane) findViewById(R.id.body_scrollpane);
		mHHeadPan = (HorizontalScrollPane) findViewById(R.id.header_scrollpane);
		// mHPan.setScrollViewListener(this);
		mVPan = (VerticalScrollPane) findViewById(R.id.body_vscrollpane);
		mVPan.setScrollViewListener(this);

		mIndicatorV = (ImageView) findViewById(R.id.indicator_v);
		mIndicatorH = (ImageView) findViewById(R.id.indicator_h);
	}

	private boolean mShowMore = false;

	public void initShoreMore(boolean visiable) {
		mShowMore = visiable;
		showMoreR(visiable);
	}

	public void toggleShowMoreL(boolean bLeft) {
		if (mShowMore) {
			showMoreL(bLeft);
			showMoreR(!bLeft);
		}
	}

	private void showMoreL(boolean visiable) {
		if (visiable) {
			mIndicatorV.setVisibility(View.VISIBLE);
		} else {
			mIndicatorV.setVisibility(View.GONE);
		}
	}

	public void setShowMore(boolean visiable) {
		mShowMore = visiable;
	}

	private void showMoreR(boolean visiable) {
		if (visiable) {
			mIndicatorH.setVisibility(View.VISIBLE);
		} else {
			mIndicatorH.setVisibility(View.GONE);
		}
	}

	public int getColumnCount() {
		return mTitles.size();
	}

	public int getRowNum() {
		return mRowIndex;
	}

	public void resetReport(boolean isFit) {
		mTableBody.removeAllViews();
		mTableVHeader.removeAllViews();
		mTableHeader.removeAllViews();
		mRowIndex = 0;
		setReportTitle(isFit);
	}

	public void resetReport() {
		mTableBody.removeAllViews();
		mTableVHeader.removeAllViews();
		mTableHeader.removeAllViews();
		mRowIndex = 0;
		setReportTitle(true);
	}

	private int mTitleSize;

	public void setTitleSize(int size) {
		mTitleSize = size;
		mScreenWidth = 480;
	}

	private int mScreenWidth;

	public void initReportTitle(List<String> data, Activity activity) {
		initReportTitle(data, true, activity);
	}

	public void initReportTitle(List<String> data, boolean isFit, Activity activity) {
		WindowManager winManager = activity.getWindowManager();
		if (winManager != null) {
			Display display = winManager.getDefaultDisplay();
			if (display != null) {
				DisplayMetrics matrics = new DisplayMetrics();
				display.getMetrics(matrics);
				mScreenWidth = matrics.widthPixels;
			}
		}

		initReportTitle(data, isFit);
	}

	private void initReportTitle(List<String> data, boolean isFit) {
		mTitles = data;
		int size = mTitles.size();
		if (size > 4) {
			((HorizontalScrollPane) findViewById(R.id.header_scrollpane)).setFillViewport(false);
			((HorizontalScrollPane) findViewById(R.id.body_scrollpane)).setFillViewport(false);
		} else {
			((HorizontalScrollPane) findViewById(R.id.header_scrollpane)).setFillViewport(true);
			((HorizontalScrollPane) findViewById(R.id.body_scrollpane)).setFillViewport(true);
		}
		setReportTitle(isFit);
	}

	private boolean mIsColumn3 = false;

	private void setReportTitle(boolean isFit) {

		if (mTitles == null || mTitles.size() == 0) {
			return;
		}
		TableRow row = new TableRow(mContext);

		int backgroundId = R.drawable.table_title;
		int size = mTitles.size();

		if (size == 3) {
			mIsColumn3 = true;
		} else {
			mIsColumn3 = false;
		}
		for (int index = 0; index < size; index++) {

			if (index == 0) {
				mCorner.setText(mTitles.get(index));
				mCorner.setBackgroundResource(backgroundId);
				mCorner.setGravity(Gravity.CENTER);
				mCorner.setTextColor(Color.WHITE);
				mCorner.setTextSize(mTitleSize);
			} else {
				TextView txCell = new TextView(mContext);
				txCell.setText(mTitles.get(index));
				txCell.setBackgroundResource(backgroundId);
				txCell.setGravity(Gravity.CENTER);
				txCell.setTextColor(Color.WHITE);
				txCell.setTextSize(mTitleSize);
				LayoutParams paramLayout = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.FILL_PARENT);
				row.addView(txCell, paramLayout);
			}
		}

		row.setGravity(Gravity.CENTER);
		TableLayout.LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		mTableHeader.addView(row, lp);
	}

	public final static int TEXT_SIZE_PS = 17;
	public final static int TITLE_SIZE_PS = 16;
	public static final int RATE_COLOR_RED = Color.rgb(146, 7, 7);
	public static final int RATE_COLOR_GREEN = Color.rgb(2, 134, 11);

	public static final int CELL_TYPE_TITLE = 0x00;
	public static final int CELL_TYPE_CLICK = 0x01;
	public static final int CELL_TYPE_NO_CLICK = 0x02;
	public static final int CELL_TYPE_TITLE_CLICK = 0x03;

	static public interface Rate {
		public static final int RATE_NONE = 0x00;
		public static final int RATE_RED = 0x01;
		public static final int RATE_GREEN = 0x02;
	}

	public void setCellListener(View.OnClickListener listener) {
		cellListener = listener;
	}

	public void addReportItem(List<SpannableString> data) {
		addReportItem(data, true);
	}

	public void addReportItem(List<SpannableString> data, boolean isFit) {
		addReportItem(data, isFit, Rate.RATE_NONE);
	}

	public void addReportItem(List<SpannableString> data, int rateType) {
		addReportItem(data, false, rateType);
	}

	public void fillEmptyRow(int column) {
		List<SpannableString> row = new ArrayList<SpannableString>();
		while (mRowIndex < FULL_ROW_NUM) {
			row.clear();
			if (mIsColumn3) {
				column = 3;
			}
			for (int index = 0; index < column; index++) {
				row.add(new SpannableString(""));
			}
			addReportItem(row);
		}
	}

	public int getYear() {
		return mYear;
	}

	public int getMonth() {
		return mMonth;
	}

	public int getDay() {
		return mDay;
	}

	public void setDateYMD(int year, int month, int day) {
		mYear = year;
		mMonth = month;
		mDay = day;
	}

	public void setDateYMD(String date) {
		SimpleWSDate wsDate = new SimpleWSDate(date);
		mYear = wsDate.getYear();
		mMonth = wsDate.getMonth();
		mDay = wsDate.getDay();
	}

	public void setNewDate(String newDate) {
		this.newDate = newDate;
	}

	public String getNewDate() {
		return newDate;
	}

	public void setReportName(String name) {
		this.mReportName = name;
	}

	public String getReportName() {
		return mReportName;
	}

	public static int checkRateType(String valueRate) {
		int type = Rate.RATE_NONE;
		if (valueRate.contains("%")) {
			valueRate = valueRate.replace("%", "");
			if (valueRate.replace("-", "").length() == 0) {
				return type;
			}
			float value = Float.valueOf(valueRate);
			if (value > 0) {
				type = Rate.RATE_RED;
			} else if (value < 0) {
				type = Rate.RATE_GREEN;
			}
		}
		return type;
	}

	private boolean isItemClick = false;

	public void setItemClick(boolean isItemClick) {
		this.isItemClick = isItemClick;
	}

	public boolean isItemClick() {
		return isItemClick;
	}

	public void addVHeader(SpannableString text, boolean isFit) {
		ReportCell txCell = new ReportCell(mContext);
		((ReportCell) txCell).setTypeMenu("menu" + mRowIndex);
		((ReportCell) txCell).setTypeItem("item: " + mRowIndex);
		txCell.setTextSize(TEXT_SIZE_PS);
		txCell.setTextColor(Color.WHITE);
		txCell.setGravity(Gravity.CENTER);
		txCell.setBackgroundResource(R.drawable.table_column);
		txCell.setText(text);
		TableLayout.LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		if (isFit)
			lp.weight = 1;
		mTableVHeader.addView(txCell, lp);
	}

	public void addReportItem(List<SpannableString> data, boolean isFit, int typeRate) {
		if (data == null) {
			return;
		}
		int resid = R.drawable.table_row0;
		if ((mRowIndex++) % 2 == 0) {
			resid = R.drawable.table_row1;
		}
		TableRow row = new TableRow(mContext);
		int columnSize = data.size();
		for (int index = 0; index < columnSize; index++) {
			LayoutParams paramLayout = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.FILL_PARENT);
			if (index == 0) {
				addVHeader(data.get(index), isFit);
			} else {
				TextView txCell = new TextView(mContext);
				txCell.setTextSize(TEXT_SIZE_PS);
				txCell.setTextColor(Color.BLACK);
				if (index == (columnSize - 1)) {
					if (typeRate == Rate.RATE_RED) {
						txCell.setTextColor(RATE_COLOR_RED);
					} else if (typeRate == Rate.RATE_GREEN) {
						txCell.setTextColor(RATE_COLOR_GREEN);
					}
				}
				txCell.setPadding(0, 0, 8, 0);
				txCell.setGravity(Gravity.RIGHT);
				txCell.setBackgroundResource(resid);
				txCell.setText(data.get(index));
				row.addView(txCell, paramLayout);
			}
		}
		row.setGravity(Gravity.CENTER);
		TableLayout.LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		if (isFit)
			lp.weight = 1;
		mTableBody.addView(row, lp);
	}

	// to check column0 rate type
	public void addReportItem(List<SpannableString> data, int column0, int type0, boolean isFit) {
		if (data == null) {
			return;
		}

		int resid = R.drawable.table_row0;
		if ((mRowIndex++) % 2 == 0) {
			resid = R.drawable.table_row1;
		}

		TableRow row = new TableRow(mContext);
		int columnSize = data.size();
		for (int index = 0; index < columnSize; index++) {
			LayoutParams paramLayout = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.FILL_PARENT);
			if (index == 0) {
				addVHeader(data.get(index), isFit);
			} else {
				TextView txCell = new TextView(mContext);
				txCell.setTextSize(TEXT_SIZE_PS);
				txCell.setTextColor(Color.BLACK);
				if (index == column0) {
					if (type0 == Rate.RATE_RED) {
						txCell.setTextColor(RATE_COLOR_RED);
					} else if (type0 == Rate.RATE_GREEN) {
						txCell.setTextColor(RATE_COLOR_GREEN);
					}
				}
				txCell.setPadding(0, 0, 8, 0);
				txCell.setGravity(Gravity.RIGHT);
				txCell.setBackgroundResource(resid);
				txCell.setText(data.get(index));
				row.addView(txCell, paramLayout);
			}
		}
		row.setGravity(Gravity.CENTER);
		TableLayout.LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		if (isFit) {
			lp.weight = 1;
		}
		mTableBody.addView(row, lp);
	}

	public void addVHeader(String text, boolean isFit, int type, String proId, String columnName, String title, int typeRate, int bgRes) {
		ReportCell txCell = new ReportCell(mContext);
		((ReportCell) txCell).setTypeMenu("menu" + mRowIndex);
		((ReportCell) txCell).setTypeItem("item: " + mRowIndex);
		txCell.setTextSize(TEXT_SIZE_PS);
		txCell.setGravity(Gravity.CENTER);
		if (type == CELL_TYPE_CLICK) {
			txCell.setTextColor(Color.BLACK);
			txCell.setBackgroundResource(bgRes);
			((ReportCell) txCell).setSelfClick(true);
			((ReportCell) txCell).setProId(proId);
			((ReportCell) txCell).setColumnName(columnName);
			((ReportCell) txCell).setTitle(title);
			txCell.setOnClickListener(cellListener);
		} else if (type == CELL_TYPE_TITLE) {
			txCell.setTextColor(Color.WHITE);
			txCell.setBackgroundResource(R.drawable.table_column);
		} else if (type == CELL_TYPE_TITLE_CLICK) {
			txCell.setTextColor(Color.WHITE);
			((ReportCell) txCell).setLinkLineWhitle();
			txCell.setBackgroundResource(R.drawable.table_column);
			((ReportCell) txCell).setSelfClick(true);
			((ReportCell) txCell).setProId(proId);
			((ReportCell) txCell).setColumnName(columnName);
			((ReportCell) txCell).setTitle(title);
			txCell.setOnClickListener(cellListener);
		} else {
			txCell.setTextColor(Color.BLACK);
			txCell.setBackgroundResource(bgRes);
		}
		txCell.setText(text);
		TableLayout.LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		if (isFit)
			lp.weight = 1;
		mTableVHeader.addView(txCell, lp);
	}

	public int getPageWidth() {
		return mScreenWidth;
	}

	private PointF mStartPos = new PointF();
	private PointF mCurrPos = new PointF();
	private boolean mScrollDone = false;

	private boolean willDoHorizontalScroll(PointF startPos, PointF currPos) {
		final float deltaYVal = mCurrPos.y - mStartPos.y;
		final float deltaXVal = mCurrPos.x - mStartPos.x;
		final int deltaY = (int) Math.abs(deltaYVal);
		final int deltaX = (int) Math.abs(deltaXVal);

		return (deltaX > deltaY);
	}

	private boolean doHorizontalScroll(PointF startPos, PointF currPos, int threshold) {
		final float deltaXVal = mCurrPos.x - mStartPos.x;

		if (Math.abs(deltaXVal) < threshold) {
			return false;
		}
		if (deltaXVal < 0) {// scroll to right?
			mHHeadPan.smoothScrollBy(getPageWidth(), 0);
			mHPan.smoothScrollBy(getPageWidth(), 0);
			toggleShowMoreL(true);
		} else {// scroll to left?
			mHHeadPan.smoothScrollBy(-getPageWidth(), 0);
			mHPan.smoothScrollBy(-getPageWidth(), 0);
			toggleShowMoreL(false);
		}

		return true;
	}

	private boolean doVerticalScroll(PointF startPos, PointF currPos) {
		final float deltaYVal = mCurrPos.y - mStartPos.y;
		final float deltaXVal = mCurrPos.x - mStartPos.x;
		final int deltaY = (int) Math.abs(deltaYVal);
		final int deltaX = (int) Math.abs(deltaXVal);

		if (deltaYVal < 0) {// scroll to upper?
			mVPan.smoothScrollBy(deltaX, deltaY);
		} else {// scroll to download?
			mVPan.smoothScrollBy(deltaX, -deltaY);
		}

		return false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		final int action = event.getAction();
		switch (action & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN: {
			// update state
			final float y = event.getY();
			final float x = event.getX();
			mStartPos.set(x, y);
			mCurrPos.set(x, y);
			mScrollDone = false;

			break;
		}
		case MotionEvent.ACTION_MOVE: {
			final float y = event.getY();
			final float x = event.getX();

			if (willDoHorizontalScroll(mStartPos, mCurrPos)) {
				if (!mScrollDone) {
					mScrollDone = doHorizontalScroll(mStartPos, mCurrPos, mScreenWidth / 4);
				}
			} else {
				doVerticalScroll(mStartPos, mCurrPos);
			}
			mCurrPos.set(x, y);
			break;
		}
		case MotionEvent.ACTION_UP: {
			if (willDoHorizontalScroll(mStartPos, mCurrPos)) {
				if (!mScrollDone) {
					mScrollDone = doHorizontalScroll(mStartPos, mCurrPos, 0);
				}
			} else {
				doVerticalScroll(mStartPos, mCurrPos);
			}
			break;
		}
		}
		return true;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		return true;
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
	}

	@Override
	public void onScrollChanged(HorizontalScrollPane scrollView, int x, int y, int oldx, int oldy) {
	}

	@Override
	public void onScrollChanged(VerticalScrollPane scrollView, int x, int y, int oldx, int oldy) {
		VerticalScrollPane sp = (VerticalScrollPane) findViewById(R.id.header_vscrollpane);
		sp.scrollTo(x, y);
	}

}
